#include "soft_dog.h"

static int g_wtd_fd = -1;
int yytd_soft_dog_open()
{
    g_wtd_fd = open("/dev/watchdog", O_RDWR);
    if(g_wtd_fd < 0)
    {
        printf("open wtd dog fail\n");
        return -1;
    }
    else
    {
        printf("g_wtd_fd = %d\n", g_wtd_fd);
    }

    int flags = WDIOS_DISABLECARD;

    return ioctl(g_wtd_fd, WDIOC_SETOPTIONS, &flags);
}

int yytd_soft_dog_close()
{
    if(g_wtd_fd <= 0)
        return 0;

    int flags = WDIOS_DISABLECARD;
    ioctl(g_wtd_fd, WDIOC_SETOPTIONS, &flags);
    flags = close(g_wtd_fd);
    g_wtd_fd = -1;

    return flags;
}

int yytd_soft_dog_enable(int flag, unsigned int interval)
{
    int ret = 0;
    if(0 == flag)
    {
        if(0 < g_wtd_fd)
        {
            int flags = WDIOS_DISABLECARD;
            ret = ioctl(g_wtd_fd, WDIOC_SETOPTIONS, &flags);
        }
        else
            ret = -1;
    }
    else if(1 == flag)
    {
        if(0 < g_wtd_fd)
        {
            int interval_tmp = interval % 8 == 0 ? interval : interval + 8;
            int flags = WDIOS_ENABLECARD;
            ret = ioctl(g_wtd_fd, WDIOC_SETOPTIONS, &flags);
            ret = ioctl(g_wtd_fd, WDIOC_SETTIMEOUT, &interval_tmp);
        }
        else
            ret = -1;
    }
    else
        ret = -1;

    return ret;
}

int yytd_soft_dog_feed_interval(unsigned int interval)
{
    int ret = 0;
    if(0 < g_wtd_fd)
    {
        int interval_tmp = interval % 8 == 0 ? interval : interval + 8;
        ret = ioctl(g_wtd_fd, WDIOC_SETTIMEOUT, &interval_tmp);
    }
    else
        ret = -1;

    return ret;
}

int yytd_soft_dog_feed(void)
{
    int ret = 0;
    if(0 < g_wtd_fd)
    {
        ret = ioctl(g_wtd_fd, WDIOC_KEEPALIVE, 0);
    }
    else
        ret = -1;

    return ret;
}

int yytd_soft_dog_init(int interval_ms)
{
    int ret = 0;
    ret += yytd_soft_dog_open();
    ret += yytd_soft_dog_enable(1, interval_ms);
    yytd_soft_dog_feed();

    return ret;
}
